package com.wx.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

/**
 * NIO
 * @author wangxun
 * @version 1.0
 * @description: NIO
 * @date 2020/12/30 5:12 下午
 */
public class SocketNioServer {


    public static void main(String[] args) throws IOException, InterruptedException {
        // 所有socketChannel集合
        LinkedList<SocketChannel> clients = new LinkedList<>();

        ServerSocketChannel server = ServerSocketChannel.open();
        //设置非阻塞
        server.configureBlocking(false);
        // 绑定端口
        server.bind(new InetSocketAddress(9999));
        System.out.println(Thread.currentThread().getName()+" server is starting");

        while (true){
            Thread.sleep(1000);
            SocketChannel client = server.accept();
            if (client != null) {
                // 不阻塞
                client.configureBlocking(false);
                System.out.println(Thread.currentThread().getName()+" client =="+client.socket().getRemoteSocketAddress());
                clients.add(client);
            }

            // 分配一个堆外的 4096B的缓冲区
            ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
            for (SocketChannel channel : clients) {
                // 读取数据到缓冲区,换回的是读取到多少数据
                int num = channel.read(buffer);
                // 读取到数据
                if(num>0){
                    // 读写翻转 ,此时用于读取buffer数据
                    buffer.flip();
                    // 构造一个buffer大小的数据
                    byte[] bytes = new byte[buffer.limit()];
                    // 将buffer数据传递到目标数组
                    buffer.get(bytes);

                    String data = new  String(bytes);
                    System.out.println(Thread.currentThread().getName()+" client =="+channel.socket().getRemoteSocketAddress()
                    +" recv :"+data);

                    // buffer 清空
                    buffer.clear();

                }
            }

        }
    }
}
